import { axios } from "@/services/axios";
import {useEffect, useMemo, useState} from "react";

function  getEnumsNameByCode(enums, enum_code)
{
  for (var i in enums) {
    if (enums[i].code === enum_code) return enums[i].name;
  }
}

function  getEnumsIsBuiltinByCode(enums, enum_code)
{
  for (var i in enums) {
    if (enums[i].code === enum_code) return enums[i].is_builtin;
  }
}

function  removeItemByKey(items, key)
{
  for (var item in items) {
    if (items[item].key === key) {
      items.splice(item, 1);
      break;
    }
    if (item.hasOwnProperty("children")) {
      const r = removeItemByKey(item, key);
      items.splice(item, 1, r)
      if (r.length !== item.length) break;
    }
  }
  return items;
}

function existItemByKey(items,key)
{
  var is_tree = false;
  for (var item in items) {
    if (items[item].key === key) {
      is_tree = true;
      break;
    }
    if (item.hasOwnProperty("children")) {
      const r = existItemByKey(item, key);
      if (r) {
        is_tree = true;
        break;
      }
    }
  }
  return is_tree;
}

function itemsHasChildren(items)
{
  var is_tree = false;
  for (var item in items) {
    if (item.hasOwnProperty("children")) {
      is_tree = true;
      break;
  }}
  return is_tree;
}

const Enums = {
  get: code => axios.get(`api/enums/${code}`),
  delete: code => axios.post(`api/enums/delete/${code}`),
  save: (code,data) => axios.post(`api/enums/${code}`, data),
  items: code => axios.get(`api/enums/items/${code}`),
  all: () => axios.get(`api/enums/all`),
  create: data => axios.post(`api/enums/all`, data),
  getEnumsNameByCode,
  getEnumsIsBuiltinByCode,
  itemsHasChildren,
  removeItemByKey,
  existItemByKey,
};

export function useQueryEnumsItems(enumcode) {
  const [optionsLoaded, setOptionsLoaded] = useState(false);
  const [options, setOptions] = useState([]);

  useEffect(() => {
    let cancelDataSourceLoading = false;
    Enums.items(enumcode).then(data => {
      if (!cancelDataSourceLoading) {
        setOptionsLoaded(true);
        setOptions(data);
    }});

    return () => {
      cancelDataSourceLoading = true;
    };
  }, [enumcode]);

  return useMemo(() => ({ optionsLoaded, options }), [optionsLoaded, options]);
}

export default Enums;
